package com.hsytech.baoinbao.signinmvp.view;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.volley.VolleyError;
import com.hsytech.baoinbao.HomeActivity;
import com.hsytech.baoinbao.R;
import com.hsytech.baoinbao.SharedPreferencesTools;
import com.hsytech.baoinbao.base.BaseActivity;
import com.hsytech.baoinbao.volleytool.ApiUrls;
import com.hsytech.baoinbao.volleytool.HttpUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by 123 on 2016/1/22.
 */
public class ActivitySignIn extends BaseActivity {
    private LinearLayout sign_in_finish;
    private EditText password, account;

    private HttpUtil.HttpCallback httpCallback = new HttpUtil.HttpCallback() {
        @Override
        public void onSuccess(int what, JSONObject response) {

            Log.d("mylog", "sign in success http token" + response.optString("result"));
            JSONObject result = response.optJSONObject("result");

            SharedPreferencesTools.writeToken(ActivitySignIn.this, result.optString("token"));
            Log.d("mylog", "sp token" + SharedPreferencesTools.getTOKEN(ActivitySignIn.this));

            Intent intent = new Intent(ActivitySignIn.this, HomeActivity.class);
            startActivity(intent);
            ActivitySignIn.this.finish();
        }

        @Override
        public void onError(int what, int type, VolleyError error) {
            showToast(R.string.msg_http_failure);
        }

        @Override
        public void onErrorMsg(int what, String msg) {
            showToast(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);
        setCenterTitleText("宝中宝");
        setLeft_button(false);
        sign_in_finish = F(R.id.sign_in_finish);
        password = F(R.id.password);
        account = F(R.id.account);

        sign_in_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkBeforePost()) {

                    Map<String, String> data = new HashMap<>();
                    data.put("user_name", account.getText().toString());
                    data.put("user_password", password.getText().toString());
                    HttpUtil.httpPostWithParams(0, ApiUrls.HTTP_LOGIN, data, httpCallback, ActivitySignIn.this);
                }

            }
        });
    }

    private boolean checkBeforePost() {

        if (account.getText().toString().equals("")) {

            showToast("请填写用户名");
            return false;
        } else if (password.getText().toString().equals("")) {

            showToast("请填写密码");
            return false;
        }
        return true;
    }

}
